/*
 * @Descripttion: 雪花ID
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2022-11-29 08:58:29
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2022-11-29 16:30:37
 */
package id

import (
	"strconv"

	"gitee.com/g_boot/gfextend/types"
	"github.com/bwmarrin/snowflake"
)

const (
	// 结点idkey
	Nodeid_key = "nodeid"
	// 默认结点ID
	Default_nodeId = int64(1)
)

func init() {
	IDGen := CreateSnowflake(1)
	Regist(IDGen.GetName(), &IDGen)
}

// 雪花id
type SnowflakeID struct {
	snowflakeNode *snowflake.Node
}

// 创建一个雪花id生成器
func CreateSnowflake(nodeid int64) SnowflakeID {
	snowflake1 := SnowflakeID{}

	snowflake1.snowflakeNode, _ = snowflake.NewNode(nodeid)

	return snowflake1
}

func (self *SnowflakeID) GetName() string {
	return "SnowflakeID"
}

func (self *SnowflakeID) GenId(pairs ...types.Pair) string {
	return strconv.FormatInt(self.SnowflakeId(pairs...), 10)
}

func (self *SnowflakeID) SnowflakeId(pairs ...types.Pair) int64 {
	if self.snowflakeNode == nil {
		nodeid := GetDefauleNodeId(pairs)
		self.snowflakeNode, _ = snowflake.NewNode(nodeid)
	}
	return self.snowflakeNode.Generate().Int64()
}

func WithNodeID(v int64) (p types.Pair) {
	return types.Pair{Key: Nodeid_key, Value: v}
}

func GetDefauleNodeId(pairs []types.Pair) int64 {
	p, ok := types.Find(Nodeid_key, pairs)
	if ok {
		result, ok := p.Int64()
		if ok {
			return result
		}
	}
	return Default_nodeId
}
